package com.ayf.payment.game.api.service.payment.faka;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.dto.MerchantCommonDTO;
import com.ayf.payment.game.api.dto.OrderAndMerchantDTO;
import com.ayf.payment.game.api.dto.platform.MerchantPaymentProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.entity.Partition;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.httpclient.HttpUtils;
import com.ayf.payment.game.api.service.payment.IPaymentService;
import com.ayf.payment.game.api.service.payment.faka.util.FaKaSignUtil;
import com.ayf.payment.game.api.utils.BigDecimalUtil;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Service
public class FaKaPaymentService extends IPaymentService {

    @Override
    public Map<String, Object> paymentUtil(Order order, Partition partition, String orderCreateStr, String traceId, String redirectUrl) {
        Map<String, Object> map=new HashMap<>();
        MerchantCommonDTO merchantDTO = merchantService.getMerchantCommon(partition.getMerchantId());
        MerchantPaymentProductDTO merchantPaymentProductDTO = systemInitialization.productDTO(order.getPayTypeId());
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(merchantPaymentProductDTO.getcId());
        BigDecimal actualOrderAmt = getActualOrderAmt(order.getAmount(),paymentChannelDTO.getId(),partition.getMerchantId());
        BaseResData baseResData = orderCreate(traceId,order,paymentChannelDTO,redirectUrl,actualOrderAmt,merchantPaymentProductDTO.getBusinessCode(),merchantDTO);
        String orderCreateUrl = "";
        if (baseResData.isProcessing()){
            LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 发卡下单失败 请求接口成功，接口响应超时", traceId, order.getMerchantId(), order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        BigDecimal randomAmt = BigDecimal.ZERO;
        order.setRandomAmt(BigDecimal.ZERO);
        if (baseResData.isSuccess()) {
            String rpsData = baseResData.getData();
            JSONObject jsonData = JSONObject.parseObject(rpsData);
            String ret_code = jsonData.getString("code");
            String ret_msg = jsonData.getString("msg");
            if ("10000".equals(ret_code)){
                orderCreateUrl = jsonData.getString("data");
                if (StringUtils.isEmpty(orderCreateUrl)){
                    LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 发卡下单失败 请求接口成功，接口返回报文 url为空",traceId,order.getMerchantId(), order.getMerchantOrderNo());
                    throw new NullSetException(traceId + "下单失败，请稍后重试！");
                }
            } else {
                LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 发卡下单失败 请求接口成功，接口返回失败 Code:{} Message:{}",traceId,order.getMerchantId(), order.getMerchantOrderNo(),ret_code,ret_msg);
                throw new NullSetException(traceId + "下单失败，请稍后重试！失败描述："+ret_msg);
            }
        } else {
            LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 发卡下单失败 请求接口失败 Code:{} Message:{}",traceId,order.getMerchantId(), order.getMerchantOrderNo(),baseResData.getRespCode(),baseResData.getRespMsg());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        LogPortal.info("{} 商户ID[{}] 商户订单号[{}] 发卡下单 通道支付URL[{}]", traceId, order.getMerchantId(), order.getMerchantOrderNo(),orderCreateUrl);
        order.setRandomAmt(randomAmt);
        order.setPayChannleName(paymentChannelDTO.getName());
        order.setPayChannleId(paymentChannelDTO.getId());
        order.setPayTypeId(merchantPaymentProductDTO.getProductId());
        order.setPayTypeName(merchantPaymentProductDTO.getProductName());
        order.setMerchantIncome(BigDecimal.ZERO);
        order.setPlatformIncome(BigDecimal.ZERO);
        order.setFee(BigDecimal.ZERO);
        order.setChannelIncome(BigDecimal.ZERO);
        orderMapper.insertSelective(order);
        map.put("code", "003");
        map.put("RedirectUrl",orderCreateUrl);
        return map;
    }


    private BaseResData orderCreate(String traceId, Order order, PaymentChannelDTO paymentChannelDTO, String redirectUrl, BigDecimal actualOrderAmt, String businessCode, MerchantCommonDTO merchantDTO){
        String methodName = "发卡下单";
        String KeyValue = paymentChannelDTO.getChannelKey();
        String parter = paymentChannelDTO.getAccountNumber();
        String returnUrl=paymentChannelDTO.getReturnUrl();
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道下单地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        if (StringUtils.isEmpty(returnUrl)){
            LogPortal.error("{} 失败，异步通知地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!returnUrl.endsWith("/")){
            returnUrl=returnUrl.concat("/");
        }
        if (!redirectUrl.endsWith("/")){
            redirectUrl=redirectUrl.concat("/");
        }

        AuthorizationURL=AuthorizationURL.concat("api/v1/pay/order");
        Map<String, String> reqParam = new TreeMap<>();
        reqParam.put("merchantId",parter);
        reqParam.put("requestId",order.getMerchantOrderNo());
        reqParam.put("notifyUrl",returnUrl.concat("gameapip/v/faka/pay/notify"));
        reqParam.put("channelType",getPayCode(businessCode));
        reqParam.put("amount",String.valueOf(BigDecimalUtil.yuanToFen(actualOrderAmt))); // 单位：分
        reqParam.put("returnUrl",redirectUrl.concat("gws/loading.html?orderNo=").concat(order.getMerchantOrderNo()));
        reqParam.put("clientIp",order.getClientIp());
        reqParam.put("gameName",order.getRechargeNumber());
        String sign= FaKaSignUtil.getSign(traceId,methodName,reqParam,KeyValue);
        reqParam.put("code",sign);
        BaseResData baseResData = HttpUtils.sendPostJson(traceId,methodName,AuthorizationURL,reqParam);
        return baseResData;
    }


    @Override
    public void queryPayOrder(OrderAndMerchantDTO dto, String traceId) {

    }


    private String getPayCode(String code){
        if("ALIPAY".equals(code) || "ANTCREDITPAY".equals(code)){
            return "ali_scan";
        } else if("WECHAT".equals(code)){
            return "wx_scan";
        } else {
            throw new NullSetException("该通道不支持充值，请更换其他通道充值！");
        }
    }

    private static void testOrderCreate(){
        PaymentChannelDTO paymentChannelDTO = getTestPaymentChannelDTO();
        Order order = new Order();
        Date currentDate = DateUtils.getNowDate();
        String orderCreateStr = DateUtils.dateToString(currentDate, DateUtils.formatPattern_full_03);
        String orderNo = "M" + orderCreateStr + SnowFlakeUtils.getUniqueId();
        order.setMerchantOrderNo(orderNo);
        order.setCreateTime(currentDate);
        order.setAmount(BigDecimal.valueOf(1));
        order.setMerchantId(1000);
        order.setClientIp("127.0.0.1");
        order.setRechargeNumber("test111");
        order.setPartitionName("111");
        String traceId = SnowFlakeUtils.getTraceId28();
        String redirectUrl = "http://uatxy.po111.cn";
        String bussinessCode = "WECHAT";

        MerchantCommonDTO merchantDTO = new MerchantCommonDTO();
        FaKaPaymentService xinYou2PaymentService = new FaKaPaymentService();
        BaseResData baseResData = xinYou2PaymentService.orderCreate(traceId,order,paymentChannelDTO,redirectUrl,order.getAmount(),bussinessCode,merchantDTO);
        System.out.println("发卡下单返回报文:"+ JSONObject.toJSONString(baseResData));
    }


    private static PaymentChannelDTO getTestPaymentChannelDTO(){
        PaymentChannelDTO paymentChannelDTO = new PaymentChannelDTO();
        paymentChannelDTO.setPaymentUrl("http://fkvip.bvmi.cn");
        paymentChannelDTO.setReturnUrl("http://uatxy.111ao.cn");
        paymentChannelDTO.setChannelKey("e1659ebb8635d468bdd19f92ec9bb659");
        paymentChannelDTO.setAccountNumber("22080888");// 商户ID
        return paymentChannelDTO;
    }

    public static void main(String[] args) {
        testOrderCreate();
    }

}
